---
title: ""
output: pdf_document
geometry: "top=1in, bottom=1in, left=1in, right=1in"
header-includes:
    - \usepackage{caption}
    - \usepackage{lscape}
---

\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}

\captionsetup[table]{labelformat=empty}


```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, dplyr, knitr, kableExtra, stats);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_incapacitation_scaled_table/src/gen_incapacitation_scaled_table.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "MAIN_RESULTS",
  "INCAP_SCALED_RATE_RESULTS",
  "INCAP_SCALED_RATE_RESULTS_WINZ_990",
  "INCAP_SCALED_RATE_RESULTS_WINZ_995",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "TABLE_CONFIG",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()
  
```


```{r}

main_results <- read_csv(cl_args$MAIN_RESULTS, show_col_types = F)
incap_scaled_rate_results <- read_csv(cl_args$INCAP_SCALED_RATE_RESULTS, show_col_types = F)
incap_scaled_rate_results_winz_990 <- read_csv(cl_args$INCAP_SCALED_RATE_RESULTS_WINZ_990, show_col_types = F)
incap_scaled_rate_results_winz_995 <- read_csv(cl_args$INCAP_SCALED_RATE_RESULTS_WINZ_995, show_col_types = F)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(outcome = value)

config <- read_yaml(cl_args$CONFIG_FILE)

table_config <- read_yaml(cl_args$TABLE_CONFIG)
source('../R/table_functions.R')

beta_se_digits <- table_config$digits$beta_se

```

\blandscape

```{r}

main_results <- main_results %>%
  filter(covariate_set == 'baseline__blocks') %>%
  mutate(min_days_required = "0",
         specification = "Count") %>%
  rename_with(.cols = matches("control_mean|ccm|treatment_mean|beta_|stderr_"), ~paste0('scaled_', .x))

incap_rate_table_outliers_dropped <- incap_scaled_rate_results %>%
  mutate(min_days_required = case_when(!grepl('days', outcome) ~ '1',
                                       TRUE ~ str_extract(outcome, '[0-9]+'))) %>%
  filter(min_days_required == "1") %>%
  mutate(specification = 'Rate')

incap_rate_table_outliers_winz <- bind_rows(
  incap_scaled_rate_results_winz_990 %>% mutate(winz_pctl = '99th'),
  incap_scaled_rate_results_winz_995 %>% mutate(winz_pctl = '99.5th')) %>%
  mutate(min_days_required = "1") %>%
  mutate(specification = glue("Rate, winsorizing outliers ({winz_pctl} pctl)"))

incap_rate_results <- bind_rows(
  main_results,
  incap_rate_table_outliers_dropped,
  incap_rate_table_outliers_winz) %>%
  filter(window == config$window) %>%
  separate(outcome, c('outcome'), '_rate', extra = 'drop') %>%
  filter(outcome %in% config$outcomes) %>%
  left_join(ylabels, by = "outcome") %>%
  mutate(pval_itt_fdrq = stats::p.adjust(pval_itt, method = "BH")) %>%
  mutate(across(.cols = matches('beta|mean|stderr|ccm'),
                .fns = ~ fmt(.x, decimals = beta_se_digits))) %>%
  mutate(across(.cols = matches('pval'),
                .fns = ~ fmt(.x, decimals = 3))) %>%
  mutate(across(everything(), ~ gsub('NA', '', .x))) %>%
  arrange(primary_component_order, specification) %>%
  mutate(outcome_order = 1:nrow(.)) %>%
  stack_stderrs_under_betas() %>%
  select(all_of(names(config$columns))) %>%
  replace(is.na(.), '')
  
incap_rate_table <- incap_rate_results %>%
  kable(booktabs = table_config$booktabs,
        longtable = table_config$longtable,
        col.names = unlist(config$columns),
        align = c(table_config$alignment$text,
                  rep(table_config$alignment$numeric,
                      length(config$columns) - 1))) %>%
  kable_styling(font_size = 10) %>%
  group_rows('Shooting & Homicide Victimizations',
             1, 8, latex_gap_space = table_config$group_rows_latex_gap_space) %>%
  group_rows('Shooting & Homicide Arrests',
             9, 16, latex_gap_space = table_config$group_rows_latex_gap_space) %>%
  group_rows('Other Serious Violent-Crime Arrests',
             17, 24, latex_gap_space = table_config$group_rows_latex_gap_space) %>%
  add_header_above(config$add_header_above) %>%
  column_spec(1, width="18em", latex_valign = 'm') %>%
  column_spec(2:11, width="3.7em", latex_valign = 'm')

incap_rate_table

# SAVE

timestamp <- get_timestamp()
writeLines(incap_rate_table, glue(cl_args$OUT_DIR, "/incapacitation_scaled_rate_up_to_date.tex"))
writeLines(incap_rate_table, glue(cl_args$OUT_DIR, "/incapacitation_scaled_rate_{timestamp}.tex"))

```

\elandscape
